// routes/knowledgePoints.js
const express = require('express');
const router = express.Router();
const auth = require('../middleware/auth'); // 引入认证中间件
const KnowledgePoint = require('../models/KnowledgePoint');

// 引入日志工具
const logger = require('../utils/logger');

// 引入向量存储服务
const { addKnowledgePointToStore } = require('../../services/vectorStoreService');

// @route   POST /api/knowledge-points
// @desc    创建一个新的知识点
// @access  Private (需要登录)
router.post('/', auth, async (req, res) => { // 在这里使用auth中间件
    try {
        const { title, content } = req.body;
        const userId = req.user.id;
        
        logger.route('KP_CREATE', 'Received create knowledge point request', { userId, title });

        const newKp = new KnowledgePoint({
            title,
            content,
            user: userId
        });
        
        logger.db('KP_CREATE', 'Saving new knowledge point to database');
        const kp = await newKp.save();
        logger.info('KP_CREATE', 'Knowledge point created successfully', { kpId: kp.id, userId });

        // 异步调用，无需等待其完成即可返回响应给用户，提升体验
        addKnowledgePointToStore(kp);

        res.json(kp);
    } catch (err) {
        logger.error('KP_CREATE', 'Server error during knowledge point creation', err);
        res.status(500).send('Server Error');
    }
});

// @route   GET /api/knowledge-points
// @desc    获取当前用户的所有知识点
// @access  Private
router.get('/', auth, async (req, res) => {
    try {
        const userId = req.user.id;
        logger.route('KP_LIST', 'Received get knowledge points request', { userId });
        
        logger.db('KP_LIST', 'Fetching knowledge points from database');
        const kps = await KnowledgePoint.find({ user: userId }).sort({ createdAt: -1 });
        logger.info('KP_LIST', 'Knowledge points fetched successfully', { count: kps.length, userId });

        res.json(kps);
    } catch (err) {
        logger.error('KP_LIST', 'Server error during knowledge points fetch', err);
        res.status(500).send('Server Error');
    }
});

// @route   GET /api/knowledge-points/:id
// @desc    获取单个知识点详情
// @access  Private
router.get('/:id', auth, async (req, res) => {
    try {
        const { id } = req.params;
        const userId = req.user.id;
        
        logger.route('KP_GET', 'Received get knowledge point request', { kpId: id, userId });

        logger.db('KP_GET', 'Fetching knowledge point from database', { id });
        const kp = await KnowledgePoint.findById(id);
        
        // 检查知识点是否存在
        if (!kp) {
            logger.warn('KP_GET', 'Knowledge point not found', { id, userId });
            return res.status(404).json({ msg: 'Knowledge point not found' });
        }
        
        // 确保是该用户自己的知识点
        if (kp.user.toString() !== userId) {
            logger.warn('KP_GET', 'User not authorized to access knowledge point', { kpId: id, userId, owner: kp.user.toString() });
            return res.status(401).json({ msg: 'Not authorized' });
        }
        
        logger.info('KP_GET', 'Knowledge point fetched successfully', { id, userId });
        res.json(kp);
    } catch (err) {
        logger.error('KP_GET', 'Server error during knowledge point fetch', err);
        // 如果ID格式不正确，返回404而不是500
        if (err.kind === 'ObjectId') {
            logger.warn('KP_GET', 'Invalid ObjectId format', { id: req.params.id });
            return res.status(404).json({ msg: 'Knowledge point not found' });
        }
        res.status(500).send('Server Error');
    }
});

// @route   PUT /api/knowledge-points/:id
// @desc    更新一个知识点
// @access  Private
router.put('/:id', auth, async (req, res) => {
    try {
        const { id } = req.params;
        const { title, content, status, reviewList } = req.body;
        const userId = req.user.id;
        
        logger.route('KP_UPDATE', 'Received update knowledge point request', { kpId: id, userId });

        // 构建更新对象
        const kpFields = {};
        if (title) kpFields.title = title;
        if (content) kpFields.content = content;
        if (status) kpFields.status = status;
        if (reviewList !== undefined) kpFields.reviewList = reviewList;
        
        logger.db('KP_UPDATE', 'Fetching knowledge point from database', { id });
        let kp = await KnowledgePoint.findById(id);
        if (!kp) {
            logger.warn('KP_UPDATE', 'Knowledge point not found', { id, userId });
            return res.status(404).json({ msg: 'Knowledge point not found' });
        }
        
        // 确保是该用户自己的知识点
        if (kp.user.toString() !== userId) {
            logger.warn('KP_UPDATE', 'User not authorized to update knowledge point', { kpId: id, userId, owner: kp.user.toString() });
            return res.status(401).json({ msg: 'Not authorized' });
        }
        
        logger.db('KP_UPDATE', 'Updating knowledge point in database', { id });
        kp = await KnowledgePoint.findByIdAndUpdate(
            id,
            { $set: kpFields },
            { new: true } // 返回更新后的文档
        );
        
        // 当内容发生变化时，才重新索引
        if (kpFields.content) {
            addKnowledgePointToStore(kp);
        }
        
        logger.info('KP_UPDATE', 'Knowledge point updated successfully', { id, userId });
        res.json(kp);
    } catch (err) {
        logger.error('KP_UPDATE', 'Server error during knowledge point update', err);
        // 如果ID格式不正确，返回404而不是500
        if (err.kind === 'ObjectId') {
            logger.warn('KP_UPDATE', 'Invalid ObjectId format', { id: req.params.id });
            return res.status(404).json({ msg: 'Knowledge point not found' });
        }
        res.status(500).send('Server Error');
    }
});

// @route   DELETE /api/knowledge-points/:id
// @desc    删除一个知识点
// @access  Private
router.delete('/:id', auth, async (req, res) => {
    try {
        const { id } = req.params;
        const userId = req.user.id;
        
        logger.route('KP_DELETE', 'Received delete knowledge point request', { kpId: id, userId });

        logger.db('KP_DELETE', 'Fetching knowledge point from database', { id });
        let kp = await KnowledgePoint.findById(id);
        if (!kp) {
            logger.warn('KP_DELETE', 'Knowledge point not found', { id, userId });
            return res.status(404).json({ msg: 'Knowledge point not found' });
        }
        
        // 确保是该用户自己的知识点
        if (kp.user.toString() !== userId) {
            logger.warn('KP_DELETE', 'User not authorized to delete knowledge point', { kpId: id, userId, owner: kp.user.toString() });
            return res.status(401).json({ msg: 'Not authorized' });
        }
        
        // 使用 findByIdAndDelete 替代 findByIdAndRemove
        logger.db('KP_DELETE', 'Deleting knowledge point from database', { id });
        await KnowledgePoint.findByIdAndDelete(id);
        logger.info('KP_DELETE', 'Knowledge point deleted successfully', { id, userId });
        
        res.json({ msg: 'Knowledge point removed' });
    } catch (err) {
        logger.error('KP_DELETE', 'Server error during knowledge point deletion', err);
        // 如果ID格式不正确，返回404而不是500
        if (err.kind === 'ObjectId') {
            logger.warn('KP_DELETE', 'Invalid ObjectId format', { id: req.params.id });
            return res.status(404).json({ msg: 'Knowledge point not found' });
        }
        res.status(500).send('Server Error');
    }
});

module.exports = router;